from datetime import datetime
from typing import Optional
from sqlalchemy.orm import Session
from sqlalchemy import desc
from .models import House, HouseDyn
from lib.database.community.models import Community


def get_by_link(*, db: Session, link: str) -> Optional[House]:
    return db.query(House).filter(House.link == link).one_or_none()


def get_newest_dyn_by_house(*, db: Session, house: House) -> HouseDyn:
    return db.query(HouseDyn).filter(HouseDyn.house_id == house.id).order_by(desc(HouseDyn.created_at)).first()


def get_recent_dyn_by_house(*, db: Session, house: House, recent_date: datetime) -> Optional[HouseDyn]:
    house_dyns = (db.query(HouseDyn).
                  filter(HouseDyn.house_id == house.id, HouseDyn.created_at >= recent_date).
                  order_by(desc(HouseDyn.created_at)).
                  all())
    if len(house_dyns) > 1:
        return house_dyns[1]
    else:
        return None


def get_recently_sold_houses(*, db: Session, community: Community, recent_date: datetime) -> list[House]:
    return (db.query(House).
            filter(House.community_id == community.id, House.is_sell_out == True,
            House.sell_out_date >= recent_date).all())


def create(*, db: Session, house_in: dict[str, str], community: Community) -> House:
    house = House(**house_in, community_id=community.id)
    db.add(house)
    db.commit()
    return house


def create_dyn(*, db: Session, house_in: dict[str, str], house: House) -> HouseDyn:
    house_dyn = HouseDyn(price=house_in["price"], house_id=house.id)
    db.add(house_dyn)
    db.commit()
    return house_dyn


def update(*, db: Session, house_in: dict[str, str], house: House) -> House:
    db_data = house.dict()

    for field in db_data:
        if field in house_in:
            setattr(house, field, house_in[field])

    db.commit()
    return house
